/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.punishinform.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseAppendixRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailAuxiliaryInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.*;
import com.icinfo.cloud.provider.punish.ucase.punishinform.mapper.CaseCollectiveDiscussMapper;
import com.icinfo.cloud.provider.punish.ucase.punishinform.mapper.CaseCollectiveDiscussPersonMapper;
import com.icinfo.cloud.provider.punish.ucase.punishinform.model.CaseCollectiveDiscuss;
import com.icinfo.cloud.provider.punish.ucase.punishinform.model.CaseCollectiveDiscussPerson;
import com.icinfo.cloud.provider.punish.ucase.punishinform.service.ICaseCollectiveDiscussService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.*;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述:  case_collective_discuss 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月17日
 */
@Service
public class CaseCollectiveDiscussServiceImpl extends MyBatisServiceSupport implements ICaseCollectiveDiscussService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseCollectiveDiscussServiceImpl.class);
    @Value("${ding.commonDingSendUrl}")
    private String commonDingSendUrl;
    @Autowired
    private CaseCollectiveDiscussMapper caseCollectiveDiscussMapper;
    @Autowired
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Autowired
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Autowired
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Autowired
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Autowired
    private CaseMainInfoMapper caseMainInfoMapper;
    @Autowired
    private SysDepartParamMapper sysDepartParamMapper;
    @Autowired
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Autowired
    private CaseCollectiveDiscussPersonMapper caseCollectiveDiscussPersonMapper;
    @Autowired
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Autowired
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private IRegisterCommonService registerCommonService;
    @Autowired
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Value("${document.url}")
    private String url;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private  ISysDepartParamService sysDepartParamService;

    /**
     * 根据案件id获取集体议案信息
     *
     * @param
     * @return {@link CaseCollectiveDiscussVo}
     * @author liyafeng
     * @date 2022/2/26
     */
    @Override
    public CaseCollectiveDiscussVo getCaseCollectiveDiscussBaseInfo(InformHtmlRequest request) {
        CaseCollectiveDiscussVo discussVo = new CaseCollectiveDiscussVo();
        Example example = new Example(CaseCollectiveDiscuss.class);
        example.createCriteria().andEqualTo("caseId", request.getCaseId());
        List<CaseCollectiveDiscuss> discussList = caseCollectiveDiscussMapper.selectByExample(example);
        CaseMainDetailInfo detailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(request.getCaseId());
        discussVo.setCaseName(detailInfo.getCaseName());
        if (CollectionUtils.isNotEmpty(discussList)) {
            BeanUtils.copyProperties(discussList.get(0), discussVo);
        } else {
            discussVo.setDiscussPlace(detailInfo.getCaseOrgAddress());
            discussVo.setCaseReason(detailInfo.getCaseName());
            discussVo.setCaseIntroduction(detailInfo.getIllegalFact());
            discussVo.setEvidenceMaterial(detailInfo.getRelateEvidence());
            discussVo.setPubishSuggestion(detailInfo.getPunishOpinion());
            Example caseReasonMainRecordExample = new Example(CaseReasonMainRecord.class);
            caseReasonMainRecordExample.createCriteria().andEqualTo("caseId", request.getCaseId()).andEqualTo("status", "1");
            List<CaseReasonMainRecord> caseReasonMainRecordList = caseReasonMainRecordMapper.selectByExample(caseReasonMainRecordExample);
            StringBuilder punishBasis = new StringBuilder();
            for (CaseReasonMainRecord caseReasonMainRecord : caseReasonMainRecordList) {
                if (punishBasis.length() > 0) {
                    punishBasis.append("、");
                }
                punishBasis.append(caseReasonMainRecord.getPunishBasis());
            }
            discussVo.setPunishBasis(punishBasis.toString());
        }
        CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(request.getCaseId());
        discussVo.setCasePartiesReasonType(mainInfo.getCasePartiesReasonType());
        discussVo.setHandleType(mainInfo.getHandleType());
        // 非分别处罚
        if (!StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), mainInfo.getHandleType())) {
            //discussVo.setDiscussConclusion(detailInfo.getDiscussConclusion());
            discussVo.setInvestConclusion(detailInfo.getInvestConclusion());
            discussVo.setPunishType(detailInfo.getPunishKinds());
            discussVo.setPunishMoney(detailInfo.getDraftPunishMoney());
            discussVo.setConfiscateIllegalMoney(detailInfo.getConfiscateIllegalMoney());
            discussVo.setConfiscateIllegalProperty(detailInfo.getConfiscateIllegalProperty());
            discussVo.setConfiscateIllegalPropertyValue(detailInfo.getConfiscateIllegalPropertyValue());
            discussVo.setPunishContent(detailInfo.getPunishContent());
        }
        // 多当事人分别处罚/多案由
        boolean multipleFlag = (StringUtils.equals(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode(), mainInfo.getCasePartiesReasonType())
                && StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), mainInfo.getHandleType()))
                || StringUtils.equals(PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode(), mainInfo.getCasePartiesReasonType());
        if (multipleFlag) {
            Example auxiliaryInfoExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryInfoExample.createCriteria().andEqualTo("caseId", request.getCaseId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryInfoExample);
            discussVo.setPunishInfoList(JSONObject.parseArray(JSONObject.toJSONString(auxiliaryInfoList), PunishInfo.class));
        }
        return discussVo;
    }

    /**
     * 保存集体议案信息
     *
     * @param caseCollectiveDiscussDto
     * @return {@link int}
     * @author liyafeng
     * @date 2022/2/26
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> saveCaseCollectiveDiscuss(CaseCollectiveDiscussDto caseCollectiveDiscussDto) {
        int num = 0;
        caseCollectiveDiscussDto.setDiscussDate(new Date());
        Example example = new Example(CaseCollectiveDiscuss.class);
        example.createCriteria().andEqualTo("caseId", caseCollectiveDiscussDto.getCaseId());
        List<CaseCollectiveDiscuss> caseCollectiveDiscussList = caseCollectiveDiscussMapper.selectByExample(example);
        if (null != caseCollectiveDiscussList && caseCollectiveDiscussList.size() > 0) {
            //存在则更新
            for (CaseCollectiveDiscuss caseCollectiveDiscuss : caseCollectiveDiscussList) {
                CaseCollectiveDiscuss updateCaseCollectiveDiscuss = new CaseCollectiveDiscuss();
                BeanUtils.copyProperties(caseCollectiveDiscussDto, updateCaseCollectiveDiscuss);
                updateCaseCollectiveDiscuss.setId(caseCollectiveDiscuss.getId());
                num = caseCollectiveDiscussMapper.updateByPrimaryKeySelective(updateCaseCollectiveDiscuss);
            }
        } else {
            //不存在则新增
            CaseCollectiveDiscuss caseCollectiveDiscuss = new CaseCollectiveDiscuss();
            BeanUtils.copyProperties(caseCollectiveDiscussDto, caseCollectiveDiscuss);
            caseCollectiveDiscuss.setId(StringUtils.uuid());
            caseCollectiveDiscuss.setCreateTime(new Date());
            caseCollectiveDiscuss.setDiscussMethod(Constant.STRING_1);
            UserDTO userInfo = UserUtil.getUserInfo();
            caseCollectiveDiscuss.setCreateUserId(userInfo.getUserId().toString());
            //保存集体议案
            num = caseCollectiveDiscussMapper.insert(caseCollectiveDiscuss);
        }
        // 非分别处罚 更新案件详情表
        if (!StringUtils.equals(HandleTypeEnum.PART_PUNISH.getCode(), caseCollectiveDiscussDto.getHandleType())) {
            CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
            updateCaseMainDetailInfo.setCaseId(caseCollectiveDiscussDto.getCaseId());
            updateCaseMainDetailInfo.setPunishKinds(caseCollectiveDiscussDto.getPunishType());
            updateCaseMainDetailInfo.setDraftPunishMoney(caseCollectiveDiscussDto.getPunishMoney());
            updateCaseMainDetailInfo.setConfiscateIllegalMoney(caseCollectiveDiscussDto.getConfiscateIllegalMoney());
            updateCaseMainDetailInfo.setConfiscateIllegalProperty(caseCollectiveDiscussDto.getConfiscateIllegalProperty());
            updateCaseMainDetailInfo.setConfiscateIllegalPropertyValue(caseCollectiveDiscussDto.getConfiscateIllegalPropertyValue());
            updateCaseMainDetailInfo.setPunishContent(caseCollectiveDiscussDto.getPunishContent());
            updateCaseMainDetailInfo.setInvestConclusion(caseCollectiveDiscussDto.getInvestConclusion());
            //设置办案结论
            updateCaseMainDetailInfo.setDiscussConclusion(caseCollectiveDiscussDto.getDiscussConclusion());
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
        }

        // 更新案件详情补充表
        if (CollectionUtils.isNotEmpty(caseCollectiveDiscussDto.getPunishInfoList())) {
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = JSONObject.parseArray(JSONObject.toJSONString(caseCollectiveDiscussDto.getPunishInfoList()), CaseMainDetailAuxiliaryInfo.class);
            for (CaseMainDetailAuxiliaryInfo auxiliaryInfo : auxiliaryInfoList) {
                caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(auxiliaryInfo);
            }
        }
        //查询案件主表
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseCollectiveDiscussDto.getCaseId());
        //附件保存
        String fileUrl = caseCollectiveDiscussDto.getFileUrl();
        JSONArray jsonArr = JSONArray.parseArray(fileUrl);
        if (jsonArr.size() > 0) {
            for (int i = 0; i < jsonArr.size(); i++) {
                JSONObject object = jsonArr.getJSONObject(i);
                CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
                caseAppendixRecord.setCaseId(caseCollectiveDiscussDto.getCaseId());
                caseAppendixRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                caseAppendixRecord.setAppendixTypeId(EvidenceTypeEnum.MATERIAL_JTYA.getCode());
                caseAppendixRecord.setAppendixUrl(object.getString("url"));
                caseAppendixRecord.setAppendixName(object.getString("name"));
                caseAppendixRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                caseAppendixRecord.setDocumentCatalogCode(caseCollectiveDiscussDto.getDocumentCatalogCode());
                caseAppendixRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                caseAppendixRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                caseAppendixRecordService.saveCaseAppendixRecord(caseAppendixRecord);
            }
        }

        //生成集体议案文书
        StageDocCommonOperateSaveDto operateSaveDto = new StageDocCommonOperateSaveDto();
        operateSaveDto.setCaseId(caseCollectiveDiscussDto.getCaseId());
        operateSaveDto.setDocumentCatalogCode(caseCollectiveDiscussDto.getDocumentCatalogCode());
        if (caseCollectiveDiscussDto.getPunishInfoList() == null) {
            caseCollectiveDiscussDto.setPunishInfoList(new ArrayList<>());
        }
        HashMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(caseCollectiveDiscussDto), HashMap.class);
        if (null != caseCollectiveDiscussDto.getDiscussStartTime()) {
            map.put("discussStartTime", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussStartTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        if (null != caseCollectiveDiscussDto.getDiscussEndTime()) {
            map.put("discussEndTime", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussEndTime(), "yyyy年M月d日HH时mm分"));
        }
        if (null != caseCollectiveDiscussDto.getDiscussDate()) {
            map.put("discussDate", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussDate(), "yyyy年M月d日"));
        }
        map.put("caseName",caseMainInfo.getCaseName());
        String orgCode = caseMainInfo.getCaseOrgCode();
        String deptCode=caseMainInfo.getCaseDeptCode();
        /*List<SysDepartParam> sysDepartParams=new ArrayList<>();
        SysDepartParam sysDepartParam=new SysDepartParam();
        String isConfigDept= Constant.STRING_0;
        Example orgExample = new Example(SysDepartParam.class);
        orgExample.createCriteria().andEqualTo("orgCode",orgCode).andIsNull("deptCode").andEqualTo("isDeleted",Constant.STRING_0);
        sysDepartParams = sysDepartParamMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(sysDepartParams)){
            sysDepartParam = sysDepartParams.get(Constant.INTEGER_0);
            isConfigDept=sysDepartParams.get(0).getIsConfigDept();
        }
        if(Constant.STRING_1.equals(isConfigDept)){
            Example deptExample = new Example(SysDepartParam.class);
            deptExample.createCriteria().andEqualTo("orgCode", orgCode).andEqualTo("deptCode",deptCode).andEqualTo("isDeleted",Constant.STRING_0);
            sysDepartParams = sysDepartParamMapper.selectByExample(example);
            if(!ObjectUtils.isEmpty(sysDepartParams)){
                sysDepartParam=sysDepartParams.get(0);
            }
        }*/
        SysDepartParam sysDepartParam =sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
        map.put("orgStandardName", sysDepartParam.getOrgStandardName());
        map.put("investConclusion", caseCollectiveDiscussDto.getInvestConclusion());
        map.put("casePartiesReasonType", caseMainInfo.getCasePartiesReasonType());
        map.put("signList",new ArrayList<>());
        operateSaveDto.setDataMap(map);
        operateSaveDto.setIsUpdateRelationTable("0");
        Map<String, Object> docMap = stageDocCommonOperateService.saveDocInfo(operateSaveDto);
        String status = MapUtils.getString(docMap, "success", "");
        if (!"true".equals(status)) {
            num = 0;
        }
        //生成议案结论
        if(StringUtils.isNotBlank(caseCollectiveDiscussDto.getDiscussConclusion())){
            //生成议案结论，发送浙政钉消息通知
            //标题：线上集体议案
            //正文：编号【台仙综执立字[2022]第000067号】的案件，已汇总议案结论，请签字确认
            Example personExample = new Example(CaseCollectiveDiscussPerson.class);
            personExample.createCriteria().andEqualTo("caseId", caseCollectiveDiscussDto.getCaseId())
                    .andIn("userType",Arrays.asList(new String[]{Constant.STRING_1,Constant.STRING_2}));;
            List<CaseCollectiveDiscussPerson> discussPersonList = caseCollectiveDiscussPersonMapper.selectByExample(personExample);
            if (!ObjectUtils.isEmpty(discussPersonList)) {
                List<String> userIds = discussPersonList.stream().map(CaseCollectiveDiscussPerson::getUserId).collect(Collectors.toList());
                String title = "线上集体议案";
                String content="编号【"+caseMainInfo.getCaseNumber() +"】的案件，已汇总议案结论，请签字确认";
                //发送浙政钉消息通知
                sendZzdMsg(userIds,title,content);
            }
        }
        return docMap;
    }
    private Map<String, Object>  generateDoc(CaseCollectiveDiscussDto caseCollectiveDiscussDto,CaseMainInfo caseMainInfo){
        int num = 0;
        //生成集体议案文书
        StageDocCommonOperateSaveDto operateSaveDto = new StageDocCommonOperateSaveDto();
        operateSaveDto.setCaseId(caseCollectiveDiscussDto.getCaseId());
        operateSaveDto.setDocumentCatalogCode(caseCollectiveDiscussDto.getDocumentCatalogCode());
        if (caseCollectiveDiscussDto.getPunishInfoList() == null) {
            caseCollectiveDiscussDto.setPunishInfoList(new ArrayList<>());
        }
        HashMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(caseCollectiveDiscussDto), HashMap.class);
        if (null != caseCollectiveDiscussDto.getDiscussStartTime()) {
            map.put("discussStartTime", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussStartTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        if (null != caseCollectiveDiscussDto.getDiscussEndTime()) {
            map.put("discussEndTime", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussEndTime(), "yyyy年M月d日HH时mm分"));
        }
        if (null != caseCollectiveDiscussDto.getDiscussDate()) {
            map.put("discussDate", DateUtils.formatDate(caseCollectiveDiscussDto.getDiscussDate(), "yyyy年M月d日"));
        }
        map.put("caseName",caseMainInfo.getCaseName());
        String orgCode = caseMainInfo.getCaseOrgCode();
        Example orgExample = new Example(SysDepartParam.class);
        orgExample.createCriteria().andEqualTo("orgCode", orgCode);
        List<SysDepartParam> sysDepartParams = sysDepartParamMapper.selectByExample(orgExample);
        if (null != sysDepartParams && sysDepartParams.size() > 0) {
            String orgStandardName = sysDepartParams.get(0).getOrgStandardName();
            map.put("orgStandardName", orgStandardName);
        }
        map.put("investConclusion", caseCollectiveDiscussDto.getInvestConclusion());
        map.put("casePartiesReasonType", caseMainInfo.getCasePartiesReasonType());
        map.put("signList",new ArrayList<>());

        operateSaveDto.setDataMap(map);
        operateSaveDto.setIsUpdateRelationTable("0");
        Map<String, Object> docMap = stageDocCommonOperateService.saveDocInfo(operateSaveDto);
        String status = MapUtils.getString(docMap, "success", "");
        if (!"true".equals(status)) {
            num = 0;
        }
        return docMap;
    }

    @Override
    public CaseCollectiveDiscussUserListVo collectiveDiscussUserSelect(String caseId) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        CaseCollectiveDiscussUserListVo result = new CaseCollectiveDiscussUserListVo();
        //查询主持人 -默认自动选中本单位的法制机构分管领导（若有多个就选中第一个）
        //包含法制机构分管领导、行政机关负责人、法制机构负责人，排序按姓名首字母abcd顺序，下拉时同时显示姓名和手机号

        //查询任务是否发布
        Example example = new Example(CaseCollectiveDiscuss.class);
        example.createCriteria().andEqualTo("caseId", caseId)
        .andEqualTo("discussMethod",Constant.STRING_2);
        List<CaseCollectiveDiscuss> caseCollectiveDiscussList = caseCollectiveDiscussMapper.selectByExample(example);
        List<CaseCollectiveDiscussPerson> existPersonList = null;
        if (null != caseCollectiveDiscussList && caseCollectiveDiscussList.size() > 0) {
            //修改的时候数据复显
            Example personExample = new Example(CaseCollectiveDiscussPerson.class);
            personExample.createCriteria().andEqualTo("caseId", caseId);
            existPersonList = caseCollectiveDiscussPersonMapper.selectByExample(personExample);
        }
        Set<CaseCollectiveDiscussUserVo> hostList = new HashSet<>();
        String roleName = "法制机构分管领导";
        //查询法制机构分管领导
        List<CaseCollectiveDiscussUserVo> fzjgfgldList = caseCollectiveDiscussMapper.getUserByOrgCodeAndRoleNameList(caseMainInfo.getCaseOrgCode(),roleName);
        roleName = "行政机关负责人";
        List<CaseCollectiveDiscussUserVo> xzjgfzrList = caseCollectiveDiscussMapper.getUserByOrgCodeAndRoleNameList(caseMainInfo.getCaseOrgCode(),roleName);
        roleName = "法制机构负责人";
        List<CaseCollectiveDiscussUserVo> fzjgfzrList = caseCollectiveDiscussMapper.getUserByOrgCodeAndRoleNameList(caseMainInfo.getCaseOrgCode(),roleName);
        roleName = "法制人员";
        List<CaseCollectiveDiscussUserVo> fzryList = caseCollectiveDiscussMapper.getUserByOrgCodeAndRoleNameList(caseMainInfo.getCaseOrgCode(),roleName);
        //办案人员列表
        List<CaseCollectiveDiscussUserVo> handlerPersonList = caseCollectiveDiscussMapper.getHandlerPersonList(caseId,null);
        //主办人员列表
        List<CaseCollectiveDiscussUserVo> mainHandlerPersonList = caseCollectiveDiscussMapper.getHandlerPersonList(caseId,Constant.STRING_1);
        //协办人员列表
        List<CaseCollectiveDiscussUserVo> coOrganizersHandlerPersonList = caseCollectiveDiscussMapper.getHandlerPersonList(caseId,Constant.STRING_2);
        addFilterUserList(hostList,fzjgfgldList,mainHandlerPersonList);
        addFilterUserList(hostList,xzjgfzrList,mainHandlerPersonList);
        addFilterUserList(hostList,fzjgfzrList,mainHandlerPersonList);
        result.setHostList(hostList);

        //单位所有人员
        List<CaseCollectiveDiscussUserVo> orgUserList = caseCollectiveDiscussMapper.getUserByOrgCodeAndRoleNameList(caseMainInfo.getCaseOrgCode(),null);

        //出席人员 - 包含本单位全部人，默认自动已选中本单位行政机关负责人、法制机构负责人、承办机构负责人
        //出席人员最后是需要发表议案建议和签字
        Set<CaseCollectiveDiscussUserVo> attendPersonList = new HashSet<>();
        addFilterUserList(attendPersonList,fzjgfgldList,mainHandlerPersonList);
        addFilterUserList(attendPersonList,xzjgfzrList,mainHandlerPersonList);
        addFilterUserList(attendPersonList,fzjgfzrList,mainHandlerPersonList);
        addFilterUserList(attendPersonList,orgUserList,mainHandlerPersonList);
        result.setAttendPersonList(attendPersonList);

        //列席人员 - 包含本单位全部人，默认自动已选中本案件全部承办人（主办/协办）和本单位全部法制人员（有多少人选中多少），列席人员不需要发表议案建议，也不需要签字
        Set<CaseCollectiveDiscussUserVo> lxPersonList = new HashSet<>();



        //汇报人员 - 取案件主办人
        Set<CaseCollectiveDiscussUserVo> reportPerson = new HashSet<>();
        addFilterUserList(reportPerson,mainHandlerPersonList,null);
        result.setReportPerson(reportPerson);

        //记录人员 记录人：包含本案件全部承办人（协办）和全部法制人员，默认自动已选中承办人里的协办（若有多个则自动选中第一个）
        Set<CaseCollectiveDiscussUserVo> recordPerson = new HashSet<>();
        addFilterUserList(recordPerson,coOrganizersHandlerPersonList,mainHandlerPersonList);
        addFilterUserList(recordPerson,fzryList,mainHandlerPersonList);
        result.setRecordPerson(recordPerson);
        if(existPersonList != null && existPersonList.size()>0){
            //设置列席人员
            List<CaseCollectiveDiscussPerson>  lxExistPersonList = existPersonList.stream().filter(s -> Constant.STRING_3.equals(s.getUserType())).collect(Collectors.toList());
            lxExistPersonList.stream().forEach(lxUser ->{
                CaseCollectiveDiscussUserVo lxPerson = new CaseCollectiveDiscussUserVo();
                lxPerson.setUserId(lxUser.getUserId());
                lxPerson.setUserName(lxUser.getUserName());
                lxPerson.setTel(lxUser.getTel());
                lxPerson.setSelected(Constant.STRING_1);
                lxPersonList.add(lxPerson);
            });

            //复现人员选中状态
            result.setHostList(setPersonSelected(result.getHostList(),existPersonList,Constant.STRING_1,false));
            result.setAttendPersonList(setPersonSelected(result.getAttendPersonList(),existPersonList,Constant.STRING_2,false));
            result.setReportPerson(setPersonSelected(result.getReportPerson(),existPersonList,Constant.STRING_4,true));
            result.setRecordPerson(setPersonSelected(result.getRecordPerson(),existPersonList,Constant.STRING_5,false));
        }
        result.setLxPersonList(lxPersonList);
        return result;
    }

    /**
     * 设置数据回显时选中
     */
    private Set<CaseCollectiveDiscussUserVo> setPersonSelected(Set<CaseCollectiveDiscussUserVo> userList,
                                   List<CaseCollectiveDiscussPerson> existList,
                                   String userType,boolean filterCustom){
        Set<CaseCollectiveDiscussUserVo> newUserList = new HashSet<>();
        if(!filterCustom){
            for(CaseCollectiveDiscussPerson existUser :existList){
                //过滤自定义用户
                if(StringUtils.isBlank(existUser.getUserId())
                        &&existUser.getUserType().equals(userType)){
                    //自定义用户
                    CaseCollectiveDiscussUserVo userVo = createUserVo(existUser);
                    userVo.setSelected(Constant.STRING_1);
                    newUserList.add(userVo);
                }
            }
        }
        for(CaseCollectiveDiscussUserVo user :userList){
            for(CaseCollectiveDiscussPerson existUser :existList){
                if(user.getUserId().equals(existUser.getUserId()) && existUser.getUserType().equals(userType)){
                    //设置为选择状态
                    user.setSelected(Constant.STRING_1);
                    newUserList.add(user);
                }
            }
        }
        newUserList.addAll(userList);
        return newUserList;
    }
    private CaseCollectiveDiscussUserVo createUserVo(CaseCollectiveDiscussPerson person){
        CaseCollectiveDiscussUserVo vo = new CaseCollectiveDiscussUserVo();
        vo.setUserId(person.getUserId());
        vo.setUserName(person.getUserName());
        vo.setUserType(person.getUserType());
        vo.setTel(person.getTel());
        return vo;
    }
    private void addFilterUserList (Set<CaseCollectiveDiscussUserVo> userList,
                                    List<CaseCollectiveDiscussUserVo> addUserList,
                                    List<CaseCollectiveDiscussUserVo> mainHandlerPersonList){
        CaseCollectiveDiscussUserVo mainHandUser = null;
        if(CollectionUtils.isNotEmpty(mainHandlerPersonList)){
            mainHandUser=mainHandlerPersonList.get(0);
            for (CaseCollectiveDiscussUserVo user:addUserList) {
                //过滤掉主办人
                if(!userList.contains(user) && (mainHandUser != null && !mainHandUser.equals(user))){
                    CaseCollectiveDiscussUserVo newUser = new CaseCollectiveDiscussUserVo();
                    BeanUtils.copyProperties(user,newUser);
                    userList.add(newUser);
                }
            }
        }else{
            for (CaseCollectiveDiscussUserVo user:addUserList) {
                //过滤掉主办人
                if(!userList.contains(user)){
                    CaseCollectiveDiscussUserVo newUser = new CaseCollectiveDiscussUserVo();
                    BeanUtils.copyProperties(user,newUser);
                    userList.add(newUser);
                }
            }
        }


    }
    /**
     * 生成集体议案任务
     * @param: [dto]
     * @return: boolean
     * @Author: wuzhihui
     * @Date: 2022/12/06
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> saveCaseCollectiveDiscussTask(CaseCollectiveDiscussUserListDto dto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        UserDTO userInfo = UserUtil.getUserInfo();
        if(userInfo == null){
            throw new BusinessException("请先登录!");
        }

        Example example = new Example(CaseCollectiveDiscuss.class);
        example.createCriteria().andEqualTo("caseId", dto.getCaseId());
        List<CaseCollectiveDiscuss> caseCollectiveDiscussList = caseCollectiveDiscussMapper.selectByExample(example);
        boolean isInsert=true;
        CaseCollectiveDiscuss dbDiscuss = null;
        if (CollectionUtils.isNotEmpty(caseCollectiveDiscussList)) {
            isInsert = false;
            dbDiscuss = caseCollectiveDiscussList.get(0);
        }

        List<CaseCollectiveDiscussPerson> allPerson = new ArrayList<>();
        //主持人
        List<CaseCollectiveDiscussPerson> hostList = createPeronList(userInfo,dto.getCaseId(),
                Constant.STRING_1,dto.getHostList());
        //出席人员
        List<CaseCollectiveDiscussPerson> attendPersonList = createPeronList(userInfo,dto.getCaseId(),
                Constant.STRING_2,dto.getAttendPersonList());
        //列席人员
        List<CaseCollectiveDiscussPerson> lxPersonList = createPeronList(userInfo,dto.getCaseId(),
                Constant.STRING_3,dto.getLxPersonList());
        //汇报人员
        List<CaseCollectiveDiscussPerson> reportPerson = createPeronList(userInfo,dto.getCaseId(),
                Constant.STRING_4,dto.getReportPerson());
        //记录人员
        List<CaseCollectiveDiscussPerson> recordPerson = createPeronList(userInfo,dto.getCaseId(),
                Constant.STRING_5,dto.getRecordPerson());
        //添加人员并检查人员是否重复
        addAndCheckUser(allPerson,hostList);
        addAndCheckUser(allPerson,attendPersonList);
        addAndCheckUser(allPerson,lxPersonList);
        addAndCheckUser(allPerson,reportPerson);
        addAndCheckUser(allPerson,recordPerson);

        //查询案件详情
        CaseMainDetailInfo detailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
        //生成集体议案信息
        CaseCollectiveDiscuss discuss = new CaseCollectiveDiscuss();
        //集体议案案件基本信息
        InformHtmlRequest request = new InformHtmlRequest();
        request.setCaseId(dto.getCaseId());
        CaseCollectiveDiscussVo caseCollectiveDiscussBaseInfo = getCaseCollectiveDiscussBaseInfo(request);
        BeanUtils.copyProperties(caseCollectiveDiscussBaseInfo,discuss);
        discuss.setId(StringUtils.uuid());
        discuss.setCaseId(dto.getCaseId());
        discuss.setDocumentCatalogCode(dto.getDocumentCatalogCode());
        discuss.setDiscussPlace("线上");
        discuss.setDiscussStartTime(dto.getDiscussStartTime());
        discuss.setDiscussEndTime(dto.getDiscussEndTime());
        discuss.setCaseReason(caseMainInfo.getCaseName());
        discuss.setCreateUserId(userInfo.getUserId().toString());

        //集体议案形式
        discuss.setDiscussMethod(Constant.STRING_2);
        discuss.setDiscussStatus(Constant.STRING_1);
        //主持人
        discuss.setHost(hostList.get(0).getUserName());
        //出席人员
        discuss.setAttendPerson(getNameSplicing(attendPersonList));
        //列席人员
        discuss.setLxPerson(getNameSplicing(lxPersonList));
        //汇报人员
        discuss.setReportPerson(getNameSplicing(reportPerson));
        //记录人员
        discuss.setRecordPerson(getNameSplicing(recordPerson));
        //案情介绍
        discuss.setCaseIntroduction(detailInfo.getIllegalFact());
        discuss.setCreateTime(new Date());


        if(!isInsert){
            //更新
            if(!Constant.STRING_2.equals(dbDiscuss.getDiscussMethod())){
                throw new BusinessException("非集体议案线上任务!");
            }
            if(Constant.STRING_2.equals(dbDiscuss.getDiscussStatus())){
                throw new BusinessException("集体议案线上任务已完成,不能修改!");
            }
        }
        //删除关联的用用户信息防止撤回操作时人员表中已有数据未清除
        deleteCollectiveDiscussRelInfo(discuss);
        //批量保存人员信息
        caseCollectiveDiscussPersonMapper.saveList(allPerson);
        caseCollectiveDiscussMapper.insert(discuss);
        //发送钉消息- 只有主持人、出席人员能收到
        List<CaseCollectiveDiscussPerson> dingMsgPersonList = new ArrayList<>();
        dingMsgPersonList.addAll(hostList);
        dingMsgPersonList.addAll(attendPersonList);
        List<String> userIds = dingMsgPersonList.stream().map(CaseCollectiveDiscussPerson::getUserId).collect(Collectors.toList());
        String title = "线上集体议案";
        String content="编号【"+caseMainInfo.getCaseNumber()
                +"】的案件，请您参与线上集体议案发表建议，起止时间："
                +discuss.getDiscussStartTime()+"至"+discuss.getDiscussEndTime();
        //发送浙政钉消息通知
        sendZzdMsg(userIds,title,content);
        CaseCollectiveDiscussDto caseCollectiveDiscussDto = new CaseCollectiveDiscussDto();
        BeanUtils.copyProperties(discuss,caseCollectiveDiscussDto);
        caseCollectiveDiscussDto.setDocumentCatalogCode(dto.getDocumentCatalogCode());
        return generateDoc(caseCollectiveDiscussDto,caseMainInfo);
    }
    /**
     * 删除集体议案关联信息（集体议案信息、人员信息、文书信息）
     * @Author: wuzhihui
     * @Date: 2022/12/13
     */
    private int deleteCollectiveDiscussRelInfo(CaseCollectiveDiscuss discuss){
        //删除集体议案和人员信息
        Example discussExample = new Example(CaseCollectiveDiscuss.class);
        discussExample.createCriteria().andEqualTo("caseId", discuss.getCaseId());
        int deleteCount = caseCollectiveDiscussMapper.deleteByExample(discussExample);
        Example personExample = new Example(CaseCollectiveDiscussPerson.class);
        personExample.createCriteria().andEqualTo("caseId", discuss.getCaseId());
        caseCollectiveDiscussPersonMapper.deleteByExample(personExample);
        //删除集体议案关联文书
        Example docExample = new Example(CaseDocumentRecord.class);
        docExample.createCriteria().andEqualTo("caseId", discuss.getCaseId())
                .andEqualTo("documentCatalogCode",discuss.getDocumentCatalogCode());
        caseDocumentRecordMapper.deleteByExample(docExample);
        return deleteCount;
    }
    /**
     * 发送浙政钉消息通知
     * @param: [userIds, title, content]
     * @return: void
     * @Author: wuzhihui
     * @Date: 2022/12/09
     */
    private void sendZzdMsg(List<String> userIds,String title,String content){
        //userIds为空不发送钉消息
        if (ObjectUtils.isEmpty(userIds)) {
            return;
        }
        JSONObject baseInfoRequest = new JSONObject();
        baseInfoRequest.put("userIds", userIds);
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        for (ZfPeopleBaseInfoVO user : baseInfo) {
            if (StringUtils.isNotBlank(user.getDingDingId())){
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", title);
                    jsonObject.put("content", content);
                    jsonObject.put("dingDingId", user.getDingDingId());
                    BaseUtil.post(commonDingSendUrl, jsonObject);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 添加并检查用户
     * @param: [allPerson, addedList]
     * @return: void
     * @Author: wuzhihui
     * @Date: 2022/12/08
     */
    private void addAndCheckUser(List<CaseCollectiveDiscussPerson> allPerson,List<CaseCollectiveDiscussPerson> addedList){
        for(CaseCollectiveDiscussPerson person:addedList){
            if(allPerson.contains(person)){
                System.out.println(CollectiveDiscussUserTypeEnum.getValueByCode(person.getUserType()));
                //throw new BusinessException(CollectiveDiscussUserTypeEnum.getValueByCode(person.getUserType()));
                throw new BusinessException(CollectiveDiscussUserTypeEnum.getValueByCode(person.getUserType())+":"+person.getUserName()+",已存在于其他类型人员,请勿重复!");
            }
            allPerson.add(person);
        }
    }





    private String getNameSplicing(List<CaseCollectiveDiscussPerson> list){
        String result = list.stream().map(personVO -> String.valueOf(personVO.getUserName())).collect(Collectors.joining("、"));
        return result;
    }
    private List<CaseCollectiveDiscussPerson> createPeronList(UserDTO userInfo,String caseId,String userType, Set<CaseCollectiveDiscussUserVo> hostList){
        List<CaseCollectiveDiscussPerson> result = new ArrayList<>();
        hostList.stream().forEach(person ->{
            CaseCollectiveDiscussPerson newPerson = new CaseCollectiveDiscussPerson();
            newPerson.setId(StringUtils.uuid());
            newPerson.setCaseId(caseId);
            newPerson.setUserId(person.getUserId());
            newPerson.setUserName(person.getUserName());
            newPerson.setUserType(userType);
            newPerson.setOrgCode(userInfo.getOrgCode());
            newPerson.setOrgName(userInfo.getOrgName());
            newPerson.setDeptCode(userInfo.getDeptCode());
            newPerson.setDeptName(userInfo.getDeptName());
            newPerson.setCreateTime(new Date());
            newPerson.setStatus(Constant.STRING_1);
            newPerson.setTel(person.getTel());
            newPerson.setSignStatus(Constant.STRING_0);
            result.add(newPerson);
        });
        return result;
    }

    private void setNormalSelected(Set<CaseCollectiveDiscussUserVo> attendPersonList){
        attendPersonList.stream().forEach(person ->{
            person.setSelected(Constant.STRING_1);
        });
    }
    /**
     * 集体议案分页列表
     */
    @Override
    public List<CaseCollectiveDiscussVo> getCaseCollectiveDiscussList(CaseCollectiveDiscussPageRequest request) {
        UserDTO userInfo = UserUtil.getUserInfo();
        request.setCaseOrgCode(userInfo.getOrgCode());
        request.setUserId(userInfo.getUserId().toString());
        PageHelper.startPage(request.getPageNum(), request.getLength(), request.getOrderBy());
        List<CaseCollectiveDiscussVo> result = caseCollectiveDiscussMapper.getCaseCollectiveDiscussList(request);
        for (CaseCollectiveDiscussVo vo:result) {
            vo.setCaseStatusName(CaseStatusEnum.getValueByCode(vo.getCaseStatus()));
            vo.setDiscussStatusName(CaseCollectiveDiscussStatusEnum.getValueByCode(vo.getDiscussStatus()));
            //查询承办人
            String caseId = vo.getCaseId();
            //1.循环设置处理人员
            Example example = new Example(CaseHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status",Constant.STRING_1);
            example.orderBy("handlePersonType").asc();
            List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
            String handPersonName = handlePersonRecords.stream().map(p -> p.getHandlePersonName()).collect(Collectors.joining(","));
            vo.setCaseHandleName(handPersonName);
            String partyName=getPartyName(vo.getCaseId());
            vo.setPartyName(partyName);
            // processOperate 处理按钮操作情况,0:无操作,不展示,1:跳转议案建议,2:跳转议案结论,3:跳转签名
            // editOperate 编辑操作权限0:无操作,不展示,1:可编辑
            // delOperate 删除操作权限,0:无操作,不展示,1:可编辑
            vo.setProcessOperate(Constant.STRING_0);
            vo.setEditOperate(Constant.STRING_0);
            vo.setDelOperate(Constant.STRING_0);
            if(Constant.STRING_1.equals(vo.getDiscussStatus())){
                //议案中
               if((Constant.STRING_1.equals(vo.getUserType())||Constant.STRING_2.equals(vo.getUserType()))
                       && StringUtils.isBlank(vo.getDiscussConclusion())
                        && StringUtils.isBlank(vo.getProposal())){
                   //主持人 出席人员 未发表议案
                   vo.setProcessOperate(Constant.STRING_1);
               }
               if(Constant.STRING_1.equals(vo.getUserType())
                        && Constant.STRING_1.equals(vo.getDiscussStatus())
                        && StringUtils.isNotBlank(vo.getProposal())
                        && StringUtils.isBlank(vo.getDiscussConclusion())){
                    //主持人 已发表议案建议 为发表议案结论,可进行议案结论
                    vo.setProcessOperate(Constant.STRING_2);
                }
                //主持人 出席人员 议案结论已发布未签名
                if((Constant.STRING_1.equals(vo.getUserType())||Constant.STRING_2.equals(vo.getUserType()))
                        && StringUtils.isNotBlank(vo.getDiscussConclusion())
                        && Constant.STRING_0.equals(vo.getSignStatus())){
                    vo.setProcessOperate(Constant.STRING_3);
                }
                //未完成,办案人可编辑可删除
                if(Constant.STRING_1.equals(vo.getDiscussStatus()) &&
                        isHandlePerson(userInfo.getUserId().toString(),handlePersonRecords)){
                    vo.setDelOperate(Constant.STRING_1);
                    vo.setEditOperate(Constant.STRING_1);
                }
            }

        }
        return result;
    }
    /**
     * 判断用户是否为办案人
     * @param: [userId, handlePersonRecords]
     * @return: boolean
     * @Author: wuzhihui
     * @Date: 2022/12/13
     */
    private boolean isHandlePerson(String userId,List<CaseHandlePersonRecord> handlePersonRecords){
        for (CaseHandlePersonRecord handlePersonRecord : handlePersonRecords){
            if(handlePersonRecord.getHandlePersonId().equals(userId)){
                return true;
            }
        }
        return false;
    }
    /**
     * 获取当事人名称
     * @author liyafeng
     * @date 2022/10/19
     * @param caseId
     * @return {@link String}
     */
    public String getPartyName(String caseId) {
        String partyName="";
        //当事人名称处理
        List<CasePartiesRecordVo> partiesRecords = getCasePartiesInfo(caseId);
        if (!ObjectUtils.isEmpty(partiesRecords)) {
            if (partiesRecords.size() > 1) {
                partyName= partiesRecords.get(0).getPartyName() + "等" + partiesRecords.size() + "个当事人";
            } else {
                partyName=partiesRecords.get(0).getPartyName();
            }
        }
        return partyName;
    }
    /**
     * 获取当事人
     * @author liyafeng
     * @date 2022/10/19
     * @param caseId
     * @return {@link List< CasePartiesRecordVo>}
     */
    private List<CasePartiesRecordVo> getCasePartiesInfo(String caseId) {
        Example queryExample = new Example(CasePartiesRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status",Constant.STRING_1);
        queryExample.setOrderByClause(" party_type desc,create_time asc ");
        List<CasePartiesRecord> casePartiesRecord = casePartiesRecordMapper.selectByExample(queryExample);
        List<CasePartiesRecordVo> parties = new ArrayList<>();
        if (ObjectUtils.isEmpty(casePartiesRecord) || casePartiesRecord.size() == 0) {
            return parties;
        } else {
            casePartiesRecord.forEach(e -> {
                CasePartiesRecordVo party = new CasePartiesRecordVo();
                BeanUtils.copyProperties(e, party);
                parties.add(party);
            });
            return parties;
        }
    }

    @Override
    public List<CaseCollectiveDiscusSproposalVo> getPersonProposalList(CaseCollectiveDiscussPersonRequest request) {
        List<String> userTypeList = Arrays.asList(new String[]{Constant.STRING_1, Constant.STRING_2});
        request.setUserTypeList(userTypeList);
        List<CaseCollectiveDiscusSproposalVo> proposalList = caseCollectiveDiscussPersonMapper.getPersonProposalList(request);
        return proposalList;
    }



    /**
     * 发表议案意见
     */
    @Override
    public boolean saveProposal(ProposalSaveDto dto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if(userInfo == null){
            throw new BusinessException("请先登录");
        }
        Example example = new Example(CaseCollectiveDiscussPerson.class);
        example.createCriteria().andEqualTo("caseId", dto.getCaseId())
                .andEqualTo("userId",userInfo.getUserId().toString())
                .andIn("userType",Arrays.asList(new String[]{Constant.STRING_1,Constant.STRING_2}));
        List<CaseCollectiveDiscussPerson> discussList = caseCollectiveDiscussPersonMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(discussList)){
            throw new BusinessException("不是出席人员不能发表议案建议!");
        }
        CaseCollectiveDiscussPerson currentDiscussPerson = discussList.get(0);
        Example updateExample = new Example(CaseCollectiveDiscussPerson.class);
        updateExample.createCriteria().
                andEqualTo("id", currentDiscussPerson.getId());
        currentDiscussPerson.setProposal(dto.getProposal());
        currentDiscussPerson.setProposalTime(new Date());
        int updateCount = caseCollectiveDiscussPersonMapper.updateByExampleSelective(currentDiscussPerson, updateExample);
        return updateCount > 0 ? true : false;
    }


    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @WorkFlowRollAnnotation
    public Map<String, Object> signConfirm(CaseCollectiveDiscussSignDto dto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        Map<String, Object> docMap;
        //查询案件状态
        Example discussExample = new Example(CaseCollectiveDiscuss.class);
        discussExample.createCriteria().andEqualTo("caseId", dto.getCaseId())
                .andEqualTo("discussMethod",Constant.STRING_2);
        List<CaseCollectiveDiscuss> discussList = caseCollectiveDiscussMapper.selectByExample(discussExample);
        if(CollectionUtils.isEmpty(discussList)){
            throw new BusinessException("该案件线上集体议案不存在!");
        }
        CaseCollectiveDiscuss discuss = discussList.get(0);
        if(Constant.STRING_2.equals(discuss.getDiscussStatus())){
            throw new BusinessException("该案件线上集体议案已完成!");
        }
        if(StringUtils.isBlank(discuss.getDiscussConclusion())){
            throw new BusinessException("当前状态不允许签字!");
        }
        Example personExample = new Example(CaseCollectiveDiscussPerson.class);
        personExample.createCriteria().andEqualTo("caseId", dto.getCaseId())
                .andEqualTo("userId",userInfo.getUserId().toString())
                .andIn("userType",Arrays.asList(new String[]{Constant.STRING_1,Constant.STRING_2}));
        List<CaseCollectiveDiscussPerson> personList = caseCollectiveDiscussPersonMapper.selectByExample(personExample);
        //查询旧文书
        CaseDocumentRecord query = new CaseDocumentRecord();
        query.setCaseId(dto.getCaseId());
        query.setDocumentCatalogCode(dto.getDocumentCatalogCode());
        query.setDocumentRecordStatus(Constant.STRING_1);
        List<CaseDocumentRecord> dbDocumentRecordList = caseDocumentRecordMapper.select(query);
        if(CollectionUtils.isEmpty(dbDocumentRecordList)){
            throw new BusinessException("文书不存在!");
        }
        if(CollectionUtils.isEmpty(personList)){
            throw new BusinessException("当前用户无需签字!");
        }
        CaseCollectiveDiscussPerson person = personList.get(0);
        if(Constant.STRING_1.equals(person.getSignStatus())){
            throw new BusinessException("已完成签字确认,请勿重复操作");
        }
        //签字流程  获取到电子签名base64->上传base64到oss生成图片地址->把图片地址放到文书内容数据里面重新生成文书
        String signBase64 = registerCommonService.getHandleSignData(userInfo.getUserId().toString());
        if(StringUtils.isBlank(signBase64)){
            throw new BusinessException("您无电子签名,请先至【掌上执法-我的】上传电子签名");
        }
        //上传签名到oss
        String fileType = checkImageBase64Format(signBase64);
        if(StringUtils.isBlank(signBase64)){
            throw new BusinessException("签名文件格式不对");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBase64", signBase64);
        //截取文件类型
        jsonObject.put("fileType", fileType);
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");

            CaseDocumentRecord oldDocumentRecord = dbDocumentRecordList.get(0);
            JSONObject docContentObject = JSON.parseObject(oldDocumentRecord.getDocumentContent());
            JSONArray signListArr;
            if(docContentObject.containsKey("signList")){
                signListArr = docContentObject.getJSONArray("signList");
            }else{
                signListArr = new JSONArray();
                docContentObject.put("signList",signListArr);
            }
            for (Object signItem : signListArr) {
                JSONObject signItemJson = (JSONObject) signItem;
                if(userInfo.getUserId().toString().equals(signItemJson.getString("userId"))){
                    throw new BusinessException("已完成签字确认,请勿重复操作");
                }
            }
            JSONObject signItem = new JSONObject();
            signItem.put("userId",userInfo.getUserId().toString());
            signItem.put("ossUrl",url);
            //放入签名
            signListArr.add(signItem);
            HashMap<String, Object> dataMap = JSONObject.parseObject(JSONObject.toJSONString(docContentObject), HashMap.class);
            //生成新的文书
            StageDocCommonOperateSaveDto operateSaveDto = new StageDocCommonOperateSaveDto();
            operateSaveDto.setDataMap(dataMap);
            operateSaveDto.setCaseId(dto.getCaseId());
            operateSaveDto.setDocumentCatalogCode(dto.getDocumentCatalogCode());
            docMap = stageDocCommonOperateService.saveDocInfo(operateSaveDto);
            String status = MapUtils.getString(docMap, "success", "");
            /*int num = 0;
            if (!"true".equals(status)) {
                num = 0;
            }*/
            //修改签字确认状态
            Example updateExample = new Example(CaseCollectiveDiscussPerson.class);
            updateExample.createCriteria().
                    andEqualTo("id", person.getId());
            person.setSignUrl(url);
            person.setSignTime(new Date());
            person.setSignStatus(Constant.STRING_1);
            caseCollectiveDiscussPersonMapper.updateByExampleSelective(person, updateExample);

            //查询是否全部签字完成
            Example personSignExample = new Example(CaseCollectiveDiscussPerson.class);
            personSignExample.createCriteria().andEqualTo("caseId", dto.getCaseId())
                    .andIn("userType",Arrays.asList(new String[]{Constant.STRING_1,Constant.STRING_2}))
                    .andNotEqualTo("userId","")
                    .andIsNotNull("userId");
            List<CaseCollectiveDiscussPerson> personSignList = caseCollectiveDiscussPersonMapper.selectByExample(personSignExample);
            boolean allSignFinish = true;
            for (CaseCollectiveDiscussPerson personSign:personSignList) {
                if (!Constant.STRING_1.equals(personSign.getSignStatus())) {
                    allSignFinish = false;
                }
            };
            //全部签字完成，流程往下走
            if(allSignFinish){
                docMap.put("workId", dto.getCaseId());
                docMap.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
                docMap.put("documentCatalogCode", dto.getDocumentCatalogCode());
                //修改集体议案意见状态
                Example discussUpdateExample = new Example(CaseCollectiveDiscuss.class);
                discussUpdateExample.createCriteria().
                        andEqualTo("id", discuss.getId());
                discuss.setDiscussStatus(Constant.STRING_2);
                caseCollectiveDiscussMapper.updateByExampleSelective(discuss, discussUpdateExample);
                
            }

        } else {
            logger.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
            throw new BusinessException("签字上传文件失败：" + jsonObject.getString("message"));
        }
        return docMap;
    }

    @Override
    public CaseCollectiveDiscussSignStatusInfoVo getSignStatusInfo(CaseCollectiveDiscussSignDto signDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseCollectiveDiscussSignStatusInfoVo result = new CaseCollectiveDiscussSignStatusInfoVo();
        BeanUtils.copyProperties(signDto,result);
        result.setNeedSign(Constant.STRING_0);
        Example discussExample = new Example(CaseCollectiveDiscuss.class);
        discussExample.createCriteria().andEqualTo("caseId", signDto.getCaseId())
                .andEqualTo("discussMethod",Constant.STRING_2);
        List<CaseCollectiveDiscuss> discussList = caseCollectiveDiscussMapper.selectByExample(discussExample);
        if(CollectionUtils.isEmpty(discussList)){
            return result;
        }
        CaseCollectiveDiscuss discuss = discussList.get(0);
        Example personExample = new Example(CaseCollectiveDiscussPerson.class);
        personExample.createCriteria().andEqualTo("caseId", signDto.getCaseId())
                .andEqualTo("userId",userInfo.getUserId().toString())
                .andIn("userType",Arrays.asList(new String[]{Constant.STRING_1,Constant.STRING_2}));
        List<CaseCollectiveDiscussPerson> personList = caseCollectiveDiscussPersonMapper.selectByExample(personExample);

        if(Constant.STRING_1.equals(discuss.getDiscussStatus())
                && StringUtils.isNotBlank(discuss.getDiscussConclusion())
                && CollectionUtils.isNotEmpty(personList)
                && Constant.STRING_0.equals(personList.get(0).getSignStatus())){
            result.setNeedSign(Constant.STRING_1);
        }
        //查询文书信息
        CaseDocumentRecord query = new CaseDocumentRecord();
        query.setCaseId(signDto.getCaseId());
        query.setDocumentCatalogCode(discuss.getDocumentCatalogCode());
        query.setDocumentRecordStatus(Constant.STRING_1);
        List<CaseDocumentRecord> dbDocumentRecordList = caseDocumentRecordMapper.select(query);
        if(CollectionUtils.isEmpty(dbDocumentRecordList)){
            throw new BusinessException("文书不存在!");
        }
        result.setDocumentUrl(dbDocumentRecordList.get(0).getDocumentUrl());
        return result;
    }

    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int deleteDiscuss(CaseCollectiveDiscussDelDto dto) {

        Example discussExample = new Example(CaseCollectiveDiscuss.class);
        discussExample.createCriteria().andEqualTo("caseId", dto.getCaseId())
                .andEqualTo("discussMethod",Constant.STRING_2);
        List<CaseCollectiveDiscuss> discussList = caseCollectiveDiscussMapper.selectByExample(discussExample);
        if(CollectionUtils.isEmpty(discussList)){
            throw new BusinessException("该案件集体议案不存在");
        }
        CaseCollectiveDiscuss discuss = discussList.get(0);
        if(Constant.STRING_2.equals(discuss.getDiscussStatus())){
            throw new BusinessException("线上集体议案已完成,删除失败");
        }
        //判断当前用户是否是案件办案人
        UserDTO userInfo = UserUtil.getUserInfo();
        //1.循环设置处理人员
        Example example = new Example(CaseHandlePersonRecord.class);
        example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("status",Constant.STRING_1);
        example.orderBy("handlePersonType").asc();
        List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
        if(!isHandlePerson(userInfo.getUserId().toString(),handlePersonRecords)){
            throw new BusinessException("非办案人员不允许删除!");
        }
        return deleteCollectiveDiscussRelInfo(discuss);
    }

    /**
     * 判断图片base64字符串的文件格式
     *
     * @param base64ImgData
     * @return
     */
    public String checkImageBase64Format(String base64ImgData) {
        if (base64ImgData.contains("data:")) {
            int start = base64ImgData.indexOf(",");
            base64ImgData = base64ImgData.substring(start + 1);
        }
        final Base64.Decoder decoder = Base64.getDecoder();
        base64ImgData = base64ImgData.replaceAll("\r|\n", "");
        base64ImgData = base64ImgData.trim();
        byte[] b = decoder.decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "jpg";
        }
        return type;
    }

}
